package com.contact;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.ocean.util.common.StringUtil;
import com.android.ocean.util.common.TranHelper;
import com.android.ocean.util.upgrade.DialogHelper;
import com.common.method.CommonData;
import com.common.method.FromFlag;
import com.common.method.ServerPath;
import com.google.android.imageloader.ImageLoader;
import com.http.AuthorizeGetTask;
import com.http.BlackAddTask;
import com.http.FriendAddTask;
import com.http.FriendListTask;
import com.http.GiftListTask;
import com.http.GiftSendTask;
import com.http.UserInfoTask;
import com.matang.R;
import com.modle.AuthorizeStruct;
import com.modle.GiftStruct;
import com.modle.User;
import com.util.AppUtil;
import com.util.OUtil;
import com.util.UserUtil;
import com.view.GiftHoriView;
import com.view.PopupWindowSelectGift;

/**
 * 
 * @ClassName:UserSimpleInfoActivity
 * @Description:TODO艺人基本信息
 * @author zhuw
 * @date 2013-8-22 下午9:45:06
 */
public class UserSimpleInfoActivity extends BaseActivity implements
		OnClickListener, FriendAddTask.CallBack, GiftSendTask.CallBack,
		UserInfoTask.CallBack, BlackAddTask.CallBack, GiftListTask.CallBack,
		AuthorizeGetTask.CallBack {
	private RelativeLayout relaEdit;
	RelativeLayout orgZqCon, gxxcCon, gxspCon, sdlwCon, zyjnCon;

	LinearLayout xcContainer, videoContainer, giftContainer;
	TextView nickNameTv, yrhTv, signTv, skillTv;
	ImageView thumbIv, sexIv, bgIv;
	Button sendMsgBtn, sendGifBtn;
	TextView l1, l2;
	PopupWindowSelectGift popWin;
	User fUser;
	User uUser;
	String fUserID;
	int fromFlag = 0;
	TextView masterSkillTv;

	ArrayList<GiftStruct> giftList = null;
	AuthorizeStruct authorizeStruct;
	private TextView tvName;
	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.act_user_simple_info);
		init();
	}

	void init() {
		TAG = "UserSimpleInfoActivity";
		mContext = UserSimpleInfoActivity.this;
		findViews();
		
		initPaneData();
		setOnCliker();

	}

	private void setOnCliker() {
		relaEdit.setOnClickListener(new OnClickListener() {
			
			
			public void onClick(View view) {
				User user =  UserUtil.readUser();
				if (user.id.equals(fUser.id)) {
					Intent intent = new Intent();
					intent.putExtra("user",fUser);
					intent.setClass(getApplicationContext(), UserBaseInfoActivity.class);
					startActivity(intent);
				}
			}
		});
		
	}

	@Override
	protected void findViews() {
		super.findViews();
		relaEdit = (RelativeLayout) findViewById(R.id.baseInfoCon);
		orgZqCon = (RelativeLayout) findViewById(R.id.baseInfoCon);
		gxxcCon = (RelativeLayout) findViewById(R.id.gxxc_con);
		gxspCon = (RelativeLayout) findViewById(R.id.gxsp_con);
		sdlwCon = (RelativeLayout) findViewById(R.id.sdlw_con);
		zyjnCon = (RelativeLayout) findViewById(R.id.zyjn_con);
		l1 = (TextView) findViewById(R.id.l1);
		l2 = (TextView) findViewById(R.id.l2);
		masterSkillTv = (TextView) findViewById(R.id.master_skill_tv);
		tvName = (TextView) findViewById(R.id.user_name);
		xcContainer = (LinearLayout) findViewById(R.id.xc_container);
		videoContainer = (LinearLayout) findViewById(R.id.video_container);
		giftContainer = (LinearLayout) findViewById(R.id.gift_container);
		nickNameTv = (TextView) findViewById(R.id.nickname_tv);
		yrhTv = (TextView) findViewById(R.id.yrh_tv);
		signTv = (TextView) findViewById(R.id.sign_tv);
		thumbIv = (ImageView) findViewById(R.id.thumb_iv);
		sexIv = (ImageView) findViewById(R.id.sex_Iv);
		bgIv = (ImageView) findViewById(R.id.bg_iv);
		skillTv = (TextView) findViewById(R.id.skill_tv);

		sendMsgBtn = (Button) findViewById(R.id.send_msg_btn);
		sendGifBtn = (Button) findViewById(R.id.send_gift_btn);
		sendGifBtn.setVisibility(View.GONE);

	}

//	/**
//	 * 加载数据
//	 */
//	private void loadUserData() {
//		// showLoading(loadingView);
//		new FriendListTask(this).execute(uID);
//
//	}


	
	public void initPaneData() {
		super.initPaneData();
		//fUserID = getIntent().getStringExtra("fUserID");
		Bundle bundle = getIntent().getExtras();//.get("fUserID");
		if (bundle != null) {
			fUser = (User) bundle.get("fUserID");
			fUser.nickName = fUser.id;
			header.headRightTv.setVisibility(View.GONE);
		}
		if (fUser == null) {
			fUser =  UserUtil.readUser();
		}
		loadUserData();
		freshUserPane();
		fromFlag = getIntent().getIntExtra("FromFlag", 0);
		uUser = UserUtil.readUser();
		header.headTitleTv.setText("好友资料");
		if (fromFlag == FromFlag.USER_SIMPLEINFO_CHAT) {
			header.headRightTv.setText("拉黑");

		} else {
			header.headRightTv.setText("加为好友");

		}

		if (fromFlag == FromFlag.USER_SIMPLEINFO_YRLIST) {
			// 如果来源艺人列表，送礼物不可点击
			sendMsgBtn.setVisibility(View.GONE);
			sendMsgBtn.setClickable(false);
		}
		
		if (fromFlag == FromFlag.USER_SIMPLEINFO_RECE_RESUME_INFO) {
			// 如果收到简历信息列表
			header.headRightTv.setText("加为好友");
			sendMsgBtn.setVisibility(View.GONE);
			sendMsgBtn.setClickable(false);
		}
		header.headRightTv.setVisibility(View.VISIBLE);
		header.headRightTv.setOnClickListener(this);
		if (fromFlag == FromFlag.USER_SIMPLEINFO_FRIENDAPPLY||fromFlag == FromFlag.USER_SIMPLEINFO_GIFT) {
			// 用户申请或礼物
			
			header.headRightTv.setVisibility(View.GONE);
			sendMsgBtn.setVisibility(View.GONE);
			sendMsgBtn.setClickable(false);
		}
		orgZqCon.setOnClickListener(this);
		gxxcCon.setOnClickListener(this);
		gxspCon.setOnClickListener(this);
		sdlwCon.setOnClickListener(this);
		sendGifBtn.setOnClickListener(this);
		sendMsgBtn.setOnClickListener(this);
		loadAuthorize();
		if (fUser.id.equals(uUser.id)) {
			header.headTitleTv.setText("个人信息");
			header.headRightTv.setVisibility(View.GONE);
		}

	}

	private void loadAuthorize() {
		showProgressDialog("");
		new AuthorizeGetTask(this).execute(uUser.id, fUserID);
	}

	private void loadUserGift() {
		showProgressDialog("");
		new GiftListTask(this).execute(GiftStruct.TYPE_RECEIVE, fUserID);
	}

	private void loadUserData() {
		showProgressDialog();
		new UserInfoTask(this).execute(fUser.id);
	}
	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		super.onRestart();
		loadUserData();
	}
	private void freshUserPane() {
		String name = fUser._user_resume;
		String userName = "";
		if (name != null) {
			try {
				userName = new JSONObject(name).getString("name");
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if ( !StringUtil.isNull(userName)) {
			tvName.setText(userName);
		}
		if ( !StringUtil.isNull(fUser.name)) {
			if(StringUtil.validateMoblie(fUser.name)){
				nickNameTv.setText(StringUtil.mobileEncry(fUser.name));
				
			}else{
				nickNameTv.setText(fUser.name);

			}
		} else {
			
			if(StringUtil.validateMoblie(fUser.nickName)){
				nickNameTv.setText(StringUtil.mobileEncry(fUser.nickName));
				
			}else{
				nickNameTv.setText(fUser.nickName);

			}
			


		}
		
		if(!StringUtil.isNull(fUser.masterSkill)){
			masterSkillTv.setText(fUser.masterSkill);
		}else{
			masterSkillTv.setVisibility(View.GONE);
		}
	//	OUtil.setThumbBg(fUser, bgIv);
		OUtil.setSexImg(fUser, sexIv);

		yrhTv.setText("好友号：" + fUser.iyrNum);
		signTv.setText(fUser.signature);
		if (!StringUtil.isListNull(fUser.skillList)) {
			StringBuffer sbs = new StringBuffer();
			for (int i = 0; i < fUser.skillList.size(); i++) {
				sbs.append(fUser.skillList.get(i).skill + "、");
			}
			skillTv.setText(sbs);
		}
		ImageLoader.get(mContext).bind(thumbIv,
				ServerPath.SERVER + fUser.thumb, null, R.drawable.default_head);

		fillAlbum();
		fillVideo();
	}

	/**
	 * 
	 * @Description:TODO填充相册
	 * @param
	 * @return void
	 * @author zhuw
	 * @date 2013-8-17 下午1:15:21
	 */
	private void fillAlbum() {

		xcContainer.removeAllViews();
		if (!StringUtil.isListNull(fUser.albumList)) {
			int len = fUser.albumList.size();
			int MAX_SHOW_NUM = 3;// 最多显示的图片
			LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
					(int) mContext.getResources().getDimension(
							R.dimen.small_img_width), (int) mContext
							.getResources().getDimension(
									R.dimen.small_img_height));
			lp.rightMargin = 20;
			if (len < 3) {
				for (int i = 0; i < len; i++) {
					ImageView iv = new ImageView(mContext);
					xcContainer.addView(iv, lp);
					iv.setOnClickListener(simpleToAlumListener);
					ImageLoader.get(mContext)
							.bind(iv,
									ServerPath.SERVER
											+ fUser.albumList.get(i).thumbUrl,
									null, R.drawable.default_head);

				}

			} else {
				for (int i = 0; i < MAX_SHOW_NUM; i++) {
					ImageView iv = new ImageView(mContext);
					xcContainer.addView(iv, lp);
					iv.setOnClickListener(simpleToAlumListener);
					ImageLoader.get(mContext)
							.bind(iv,
									ServerPath.SERVER
											+ fUser.albumList.get(i).thumbUrl,
									null, R.drawable.default_head);

				}
			}

		}

	}

	/**
	 * 
	 * @Description:TODO填充video
	 * @param
	 * @return void
	 * @author zhuw
	 * @date 2013-9-4 下午4:44:59
	 */
	private void fillVideo() {

		videoContainer.removeAllViews();
		if (!StringUtil.isListNull(fUser.videoList)) {
			int len = fUser.videoList.size();
			int MAX_SHOW_NUM = 3;// 最多显示的图片
			LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
					(int) mContext.getResources().getDimension(
							R.dimen.video_small_img_width), (int) mContext
							.getResources().getDimension(
									R.dimen.video_small_img_height));
			lp.rightMargin = 20;
			if (len < 3) {
				for (int i = 0; i < len; i++) {
					ImageView iv = new ImageView(mContext);
					videoContainer.addView(iv, lp);
					iv.setOnClickListener(simpleToVideoListener);
					iv.setImageResource(R.drawable.video_i);
				}

			} else {
				for (int i = 0; i < MAX_SHOW_NUM; i++) {
					ImageView iv = new ImageView(mContext);
					videoContainer.addView(iv, lp);
					iv.setOnClickListener(simpleToVideoListener);
					iv.setImageResource(R.drawable.video_i);

				}
			}

		}

	}

	void fillGift() {

		giftContainer.removeAllViews();
		if (!StringUtil.isListNull(giftList)) {
			int len = giftList.size();
			LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
					(int) mContext.getResources().getDimension(
							R.dimen.gift_small_img_width), (int) mContext
							.getResources().getDimension(
									R.dimen.gift_small_img_height));
			lp.rightMargin = 20;
			for (int i = 0; i < len; i++) {
				if (CommonData.getGiftMap().containsKey(
						giftList.get(i).giftType)) {
					GiftHoriView iv = new GiftHoriView(mContext);
					giftContainer.addView(iv, lp);
					iv.setGiftNum(giftList.get(i).giftNum);
					iv.setImageResource(CommonData.getGiftMap().get(
							giftList.get(i).giftType));
				}
			}

		}

	}

	OnClickListener simpleToAlumListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			Bundle b = new Bundle();
			b.putSerializable("user", fUser);
			//TranHelper.toAct(mContext, UserAlbumsActivity.class, b);

		}
	};
	OnClickListener simpleToVideoListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			Bundle b = new Bundle();
			b.putSerializable("user", fUser);
			//TranHelper.toAct(mContext, UserVideoActivity.class, b);

		}
	};

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.headRight: {
			if (fromFlag == FromFlag.USER_SIMPLEINFO_CHAT) {
				showProgressDialog("拉入黑名单...");
				new BlackAddTask(this)
						.execute(UserUtil.readUser().id, fUser.id);

			} else {
				showProgressDialog("添加好友中...");
				new FriendAddTask(this).execute(UserUtil.readUser().id,
						fUser.id);

			}

			break;
		}

		case R.id.send_msg_btn: {
			// Bundle b = new Bundle();
			// b.putSerializable("user", fUser);
			// TranHelper.toActClearTop(mContext, ChatActivity.class, b);
			finish();
			break;
		}
		case R.id.send_gift_btn: {
			showChosPop();
			break;
		}
		case R.id.sdlw_con: {
			AppUtil.giftListSwitch(mContext, fUser.id, GiftStruct.TYPE_RECEIVE,
					"收到的礼物");
			break;
		}

		}

	}

	/**
	 * 
	 * @Description:TODO根据权限判断相册、视频、简历、哪些需要显示
	 * @param
	 * @return void
	 * @author zhuw
	 * @date 2013-9-29 下午10:48:46
	 */
	private void filterView() {
		loadUserData();
		loadUserGift();
		if (authorizeStruct.canViewAlbum) {
			gxxcCon.setVisibility(View.VISIBLE);
			l1.setVisibility(View.VISIBLE);

		}
		if (authorizeStruct.canViewVideo) {
			gxspCon.setVisibility(View.VISIBLE);
			l2.setVisibility(View.VISIBLE);
		}
		if (authorizeStruct.canViewResume) {

		}

	}

	OnClickListener giftClick = new OnClickListener() {

		@Override
		public void onClick(View v) {

			switch (v.getId()) {
			case R.id.g0:
				checkSendGift(0);
				break;
			case R.id.g1:
				checkSendGift(1);
				break;
			case R.id.g2:
				checkSendGift(2);
				break;
			case R.id.g3:
				checkSendGift(3);
				break;
			case R.id.g4:
				checkSendGift(4);
				break;

			case R.id.g5:
				checkSendGift(5);
				break;

			}

		}
	};

	private void showChosPop() {

		popWin = new PopupWindowSelectGift(mContext, giftClick);
		// 显示窗口
		popWin.showAtLocation(
				UserSimpleInfoActivity.this.findViewById(R.id.main),
				Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0);
		// 设置layout在PopupWindow中显示的位置

	}

	private void dismisPop() {
		if (popWin != null && popWin.isShowing()) {
			popWin.dismiss();
		}

	}

	@Override
	public void procError(String msg) {
		dismissProgressDialog();
		AppUtil.tsMsg(mContext, msg);

	}

	@Override
	public void procAddFriend(String data) {
	//添加成功返回
		dismissProgressDialog();
		AppUtil.tsMsg(mContext, data);
		header.headRightTv.setVisibility(View.GONE);
		Bundle b = new Bundle();
		b.putSerializable("user", fUser);
		TranHelper.toAct(UserSimpleInfoActivity.this, ChatActivity.class, b);
		YrListActivity.instance.finish();
		UserSimpleInfoActivity.this.finish();


	}

	private void checkSendGift(final int giftNum) {

		DialogHelper.Confirm(mContext, null, "亲,赠送此礼物您需支付人民币"
				+ CommonData.getGiftPriceMap().get(giftNum + "") + "元,是否支付?",
				"是", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
//						Product p = new Product();
//						p.subject = "送礼物";
//						p.price = CommonData.getGiftPriceMap()
//								.get(giftNum + "") + "";
//						p.body = CommonData.getGiftDescMap().get(giftNum + "");
//						doPay(p, giftNum);

					}
				}, "取消", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {

					}
				});
	}

	private void sendGift(int num) {
		dismisPop();
		showProgressDialog("礼物发送中...");
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("sendId", uUser.id);
		map.put("receiveId", fUser.id);
		map.put("quantity", 1);
		map.put("gift", num);
		new GiftSendTask(this).execute(map);

	}

	@Override
	public void procGiftSend(String result) {
		dismissProgressDialog();
		AppUtil.tsMsg(mContext, "惊喜哦!");
	}

	@Override
	public void procUserInfoData(User data) {
		dismissProgressDialog();
		fUser = data;
		freshUserPane();

	}


	public void procUserInfoError(String msg) {
		AppUtil.tsMsg(mContext, "获取用户信息失败：" + msg);

		finish();
	}

	@Override
	public void procBlackAdd(String data) {
		dismissProgressDialog();
		AppUtil.tsMsg(mContext, "操作成功");

	}

	@Override
	public void procGiftListData(ArrayList<GiftStruct> dataList) {
		dismissProgressDialog();
		this.giftList = dataList;
		fillGift();
	}

	@Override
	public void procAuthGetSus(AuthorizeStruct struct) {
		dismissProgressDialog();
		authorizeStruct = struct;
		filterView();

	}

	@Override
	public void procAuthGetFailed() {
		dismissProgressDialog();
	//	AppUtil.tsMsg(mContext, "权限获取失败");

	}

//	/********************** 支付宝START *****************************************/
//	private static final int RQF_PAY = 1;
//	Handler mHandler = new Handler() {
//		public void handleMessage(android.os.Message msg) {
//			Result.sResult = (String) msg.obj;
//
//			switch (msg.what) {
//			case RQF_PAY: {
//				String resultStatus = Result.getResultStatus();
//
//				if (!StringUtil.isNull(resultStatus)
//						&& Result.sError.containsKey(resultStatus)) {
//					if (resultStatus.equalsIgnoreCase("9000")) {
//						int giftNum = msg.arg1;
//						sendGift(giftNum);
//
//					}
//					Toast.makeText(mContext,
//							Result.sError.get(Result.getResultStatus()),
//							Toast.LENGTH_SHORT).show();
//				} else {
//
//					AppUtil.tsMsg(mContext, "支付失败,未知错误");
//
//				}
//
//			}
//				break;
//			default:
//				break;
//			}
//		};
//	};

//	public void doPay(Product pro, final int giftNum) {
//		try {
//			String info = AliPayUtil.getNewOrderInfo(pro);
//			String sign = Rsa.sign(info, Keys.PRIVATE);
//			sign = URLEncoder.encode(sign);
//			info += "&sign=\"" + sign + "\"&" + AliPayUtil.getSignType();
//			Log.i("ExternalPartner", "start pay");
//			Result.sResult = null;
//			Log.i(TAG, "info = " + info);
//			final String orderInfo = info;
//			new Thread() {
//				public void run() {
//					String result = new AliPay(UserSimpleInfoActivity.this,
//							mHandler).pay(orderInfo);
//
//					Log.i(TAG, "result = " + result);
//					Message msg = new Message();
//					msg.what = RQF_PAY;
//					msg.obj = result;
//					msg.arg1 = giftNum;
//					mHandler.sendMessage(msg);
//				}
//			}.start();
//
//		} catch (Exception ex) {
//			ex.printStackTrace();
//			Toast.makeText(UserSimpleInfoActivity.this,
//					R.string.remote_call_failed, Toast.LENGTH_SHORT).show();
//		}
//	}

	/********************** 支付宝END *****************************************/
}
